
<template>
  <div>
    <el-select v-model="selectedProvince" placeholder="请选择省" style="width: 120px; margin-right: 8px;">
      <el-option v-for="item in provinces" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-select v-model="selectedCity" placeholder="请选择市" style="width: 120px; margin-right: 8px;" :disabled="!cities.length">
      <el-option v-for="item in cities" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-select v-model="selectedDistrict" placeholder="请选择区/县" style="width: 120px;" :disabled="!districts.length">
      <el-option v-for="item in districts" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <div style="margin-top: 16px;">
      <span>省：{{ form.province }}</span>
      <span style="margin-left: 16px;">市：{{ form.city }}</span>
      <span style="margin-left: 16px;">区县：{{ form.district }}</span>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, computed, reactive } from 'vue'
import { regionData } from 'element-china-area-data'

const provinces = ref(regionData.map(p => ({ label: p.label, value: p.value, children: p.children })))
const cities = ref<any[]>([])
const districts = ref<any[]>([])

const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistrict = ref('')
const form = reactive({
  province: '',
  city: '',
  district: ''
})
watch(selectedProvince, (val) => {
  const province = provinces.value.find(p => p.value === val)
  cities.value = province?.children || []
  selectedCity.value = ''
  districts.value = []
  selectedDistrict.value = ''
  // 省名赋值
  form.province = getLabelByCode(val, provinces.value)
  form.city = ''
  form.district = ''
})
watch(selectedCity, (val) => {
  const city = cities.value.find(c => c.value === val)
  districts.value = city ? city.children : []
  selectedDistrict.value = ''
  // 市名赋值
  form.city = getLabelByCode(val, cities.value)
  form.district = ''
})
watch(selectedDistrict, (val) => {
  // 区县名赋值
  form.district = getLabelByCode(val, districts.value)
})

function getLabelByCode(code: any, list: any[]) {
  const item = list.find((i: any) => i.value === code)
  return item ? item.label : ''
}
</script>
